package com.rpc.core.loadbalance.impl;

import com.rpc.core.holder.rag.RegInfoEnhancer;
import com.rpc.core.loadbalance.LoadBalance;
import com.rpc.core.remoting.Client;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
//sticking
public class StickingLoadBalance implements LoadBalance {

    private volatile RegInfoEnhancer enhancer;

    @Override
    public RegInfoEnhancer get(List<RegInfoEnhancer> list) {
        if (enhancer != null && list.contains(enhancer)) {
            Client client = enhancer.getClient();
            if (client != null) {
                return enhancer;
            }
        }


        synchronized (this) {
            if (enhancer != null) {
                return enhancer;
            }
            //random
            ArrayList<RegInfoEnhancer> enhancers = new ArrayList<>(list);
            HashSet<RegInfoEnhancer> useFailSet = new HashSet<>();

            for (; ; ) {
                int index = new Random().nextInt(list.size());
                RegInfoEnhancer enhancer = enhancers.get(index);

                if (useFailSet.contains(enhancer)) {
                    continue;
                }
                Client client = enhancer.getClient();
                if (client != null) {
                    this.enhancer = enhancer;
                    return this.enhancer;
                } else {
                    if (enhancers.size() == useFailSet.size()) {
                        return null;
                    }
                    useFailSet.add(enhancer);
                }

            }
        }

    }
}
